<template>
  <div class="register-container">
    <h2 class="register-title">用户注册</h2>
    <a-form ref="formRef" :model="formState" :rules="rules">
      <!-- 学号/工号输入框 -->
      <a-form-item
        class="form-item"
        name="userId"
        :rules="[{ required: true, message: '请输入学号或工号' }]"
      >
        <a-input
          v-model:value="formState.userId"
          placeholder="请输入学号或工号"
          class="input-with-icon"
          type="number"
        >
          <template #prefix>
            <UserOutlined class="icon" />
          </template>
        </a-input>
      </a-form-item>

      <!-- 帮区ID输入框 -->
      <a-form-item
        class="form-item"
        name="bandId"
        :rules="[{ required: true, message: '请输入帮区ID' }]"
      >
        <a-input
          v-model:value="formState.bandId"
          placeholder="请输入帮区ID"
          class="input-with-icon"
          type="number"
        >
          <template #prefix>
            <TeamOutlined class="icon" />
          </template>
        </a-input>
      </a-form-item>

      <!-- 密码输入框 -->
      <a-form-item
        class="form-item"
        name="password"
        :rules="[{ required: true, message: '请输入密码' }]"
      >
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入密码"
          class="input-with-icon"
          @keyup.enter="handleSubmit"
        >
          <template #prefix>
            <LockOutlined class="icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <!-- 邮箱输入框 -->
      <a-form-item
        class="form-item"
        name="email"
        :rules="[{ type: 'email', message: '请输入有效的邮箱地址' }]"
      >
        <a-input
          v-model:value="formState.email"
          placeholder="请输入邮箱地址"
          class="input-with-icon"
        >
          <template #prefix>
            <MailOutlined class="icon" />
          </template>
        </a-input>
      </a-form-item>

      <!-- 手机号输入框 -->
      <a-form-item
        class="form-item"
        name="phone"
        :rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
      >
        <a-input v-model:value="formState.phone" placeholder="请输入手机号" class="input-with-icon">
          <template #prefix>
            <PhoneOutlined class="icon" />
          </template>
        </a-input>
      </a-form-item>

      <!-- 用户角色选择 -->
      <a-form-item class="form-item">
        <a-radio-group
          v-model:value="formState.role"
          style="display: flex; justify-content: center"
        >
          <a-radio value="student">学生</a-radio>
          <a-radio value="teacher">教师</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 学生姓名输入框（仅当角色为学生时显示） -->
      <a-form-item
        v-if="formState.role === 'student'"
        class="form-item"
        name="studentName"
        :rules="[{ required: true, message: '请输入学生姓名' }]"
      >
        <a-input v-model:value="formState.studentName" placeholder="请输入学生姓名" />
      </a-form-item>

      <!-- 教师姓名输入框（仅当角色为教师时显示） -->
      <a-form-item
        v-if="formState.role === 'teacher'"
        class="form-item"
        name="teacherName"
        :rules="[{ required: true, message: '请输入教师姓名' }]"
      >
        <a-input v-model:value="formState.teacherName" placeholder="请输入教师姓名" />
      </a-form-item>

      <!-- 注册按钮 -->
      <a-form-item class="form-item">
        <a-button type="primary" block html-type="submit" @click="handleSubmit">注册</a-button>
      </a-form-item>
    </a-form>

    <!-- 已有账号提示 -->
    <div class="login-link">
      还有账号？
      <a href="javascript:;" @click="handleGoToLogin" class="text-blue-500 hover:underline"
        >点击登录</a
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  PhoneOutlined,
  TeamOutlined
} from '@ant-design/icons-vue';
import UserDao from '@/daos/user_dao';

const router = useRouter();
const userDao = new UserDao();
const formRef = ref();

// 表单数据
interface FormState {
  userId: number | null;
  bandId: number | null;
  password: string;
  email: string;
  phone: string;
  role: 'student' | 'teacher';
  studentName: string;
  teacherName: string;
}

const formState = reactive<FormState>({
  userId: null,
  bandId: null,
  password: '',
  email: '',
  phone: '',
  role: 'student',
  studentName: '',
  teacherName: ''
});

// 表单验证规则
const rules = {
  commentId: [
    { required: true, message: '请输入学号或工号' },
    { type: 'number', message: '必须为数字' }
  ],
  userId: [
    { required: true, message: '请输入帮区ID' },
    { type: 'number', message: '必须为数字' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码长度不能少于6位' }
  ]
};

const handleGoToLogin = () => {
  router.push('/login');
};

// 提交注册
const handleSubmit = async () => {
  try {
    // 1. 表单验证
    await formRef.value.validate();

    // 2. 确保数字类型转换
    const payload = {
      userId: Number(formState.userId),
      bandId: Number(formState.bandId),
      password: formState.password,
      email: formState.email,
      phone: formState.phone,
      role: formState.role,
      ...(formState.role === 'student'
        ? { studentName: formState.studentName }
        : { teacherName: formState.teacherName })
    };

    console.log('注册信息:', payload);

    // 3. 调用addUser方法
    const response = await userDao.addUser(
      payload.userId,
      payload.bandId,
      payload.password,
      payload.email,
      payload.phone,
      payload.role,
      payload.studentName,
      payload.teacherName,
      payload.userId
    );

    // 4. 处理响应
    if (response.data.code === 200) {
      message.success('注册成功！');
      router.push('/login');
    } else {
      message.error(response.data.message || '注册失败');
    }
  } catch (error: any) {
    if (error.errorFields) {
      message.warning('请填写完整的注册信息');
    } else {
      console.error('注册错误:', error);
      message.error(error.message || '注册过程中发生错误');
    }
  }
};
</script>

<style scoped>
.register-container {
  width: 400px;
  margin: 2em auto;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.register-title {
  text-align: center;
  margin-bottom: 25px;
  font-size: 24px;
  color: #1890ff;
}

.form-item {
  margin-bottom: 20px;
}

.input-with-icon {
  width: 100%;
  border-radius: 4px;
  padding: 10px 15px 10px 35px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s;
}

.input-with-icon:hover {
  border-color: #40a9ff;
}

.input-with-icon:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.icon {
  color: rgba(0, 0, 0, 0.25);
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #1890ff;
  transition: color 0.3s;
}

.login-link a:hover {
  color: #40a9ff;
}
</style>
